package com.websocket.service;

import com.websocket.converter.MessageConverter;
import com.websocket.event.EventPublisher;
import com.websocket.exception.PrincipalNotFoundException;
import org.java_websocket.WebSocket;

import java.security.Principal;

/**
 * 消息发布器，在程序中可以使用该对象发布消息
 * <p>在 {@link com.websocket.config.WebSocketBeanInitializer} 中已被注为 bean
 */
public class WebSocketTemplate {

    private WebSocketServer server;
    private MessageConverter converter;
    private EventPublisher publisher;

    public void setConverter(MessageConverter converter) {
        this.converter = converter;
    }
    public void setServer(WebSocketServer server) {
        this.server = server;
    }
    public void setPublisher(EventPublisher publisher) {
        this.publisher = publisher;
    }

    public void sendToAll(Object message) {
        String stringify = converter.stringify(message);
        server.broadcast(stringify);
        publisher.publishPublishEvent(server, null, stringify, true);
    }

    public void sendTo(Principal principal, Object message) throws PrincipalNotFoundException {
        WebSocket connection = server.getConnection(principal);
        if (connection == null)
            throw new PrincipalNotFoundException(principal);

        sendTo(connection, message);
    }

    public void sendTo(WebSocket conn, Object message) {
        String stringify = converter.stringify(message);
        conn.send(stringify);
        Attachment attachment = conn.getAttachment();
        publisher.publishPublishEvent(server, attachment.getPrincipal(), stringify, true);
    }
}
